package com.example.demo;

/**
 * @Author lizhien (zhien.li@nascent.cn)
 * @Date 2020/8/4 19:47
 * @Version 1.0.0
 * @Description com.example.demo
 */


import lombok.SneakyThrows;

import java.util.concurrent.*;

public class ThreadPool {

    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newFixedThreadPool(5);
        for (int i = 1; i <= 100; i++) {
            final int ii = i;
            System.out.println("now is " + i);
            cachedThreadPool.execute(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    try {
                        Thread.sleep(ii * 100);
                        System.out.println("线程名称：" + Thread.currentThread().getName() + "，执行" + ii);
                    } catch (InterruptedException e) {e.printStackTrace();}
                }
            });
        }
    }

    public static ExecutorService getSingleThreadExecutor() {
//        return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,
//            0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));
        return Executors.newSingleThreadExecutor();
    }

    public static ExecutorService getCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
    }

    public static ExecutorService getFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    }

    //创建一个定长线程池，支持定时及周期性任务执行。延迟执行
    public void ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        //this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler);
    }
}
